package com.example.e

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.baidu.location.BDLocation
import com.baidu.location.BDLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.MapStatusUpdate
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.model.LatLng
import com.example.e.Adapter.ShouhuoAddressAdapter
import com.example.e.data.ShouhuoAddress
import kotlinx.android.synthetic.main.activity_location.*
import kotlinx.android.synthetic.main.activity_search.*
import java.io.*
import java.lang.StringBuilder

class LocationActivity : AppCompatActivity() {

    private val shouhuo_address_data = ArrayList<ShouhuoAddress>()
    private val file_name2 = "shouhuo_address"


    var mLocationClient: LocationClient? = null
    private val myListener = MyLocationListener()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        SDKInitializer.initialize(applicationContext) // 必须在这个位置初始化

        setContentView(R.layout.activity_location)
        getPromission()
        // 初始化定位客户端

        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps
        option.setCoorType("bd09ll") // 设置坐标类型
        option.setScanSpan(1000)
        backHome.setOnClickListener{
            finish()
        }

        initLocation()
        add_address.setOnClickListener(){
            val intent = Intent(this,AddAddressActivity::class.java)
            startActivityForResult(intent,1)
        }



        //recyclerviewshouhuoAddress.layoutManager = LinearLayoutManager(this)
        val layoutManager = LinearLayoutManager(this)
        recyclerviewshouhuoAddress.layoutManager = layoutManager
        load()
        show()
        refreshAddress()

        ivClearaddress.setOnClickListener(){
            shouhuo_address_data.clear()
            refreshAddress()
            save()
        }

    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode) {
            1 -> if (resultCode == Activity.RESULT_OK) {
                val shouhuo_name = data?.getStringExtra("shouhuo_name")
                val shouhuo_number = data?.getStringExtra("shouhuo_number")
                val shouhuo_address = data?.getStringExtra("shouhuo_address")


                if (shouhuo_name == null || shouhuo_number == null || shouhuo_address == null) {
                    Toast.makeText(this, "请输入", Toast.LENGTH_LONG).show()
                }
                else{
                    //shouhuo_address_data.remove(ShouhuoAddress(shouhuo_name))
                    shouhuo_address_data.add(0, ShouhuoAddress(shouhuo_name,shouhuo_number,shouhuo_address))
                    save()
                    show()
                    refreshAddress()
                }

                //Toast.makeText(this, "${shouhuo_name}", Toast.LENGTH_LONG).show()
            }
        }
    }
    private fun getPromission(){
        // 定义一个权限列表；只要有一个权限未通过，则权限不对
        val permissionList = ArrayList<String>()
        if(ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        if(ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }

        if(ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(android.Manifest.permission.ACCESS_COARSE_LOCATION)
        }

        if(ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(android.Manifest.permission.READ_PHONE_STATE)
        }


        if(ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ){
            // 未授权，则加入到未授权列表中
            permissionList.add(android.Manifest.permission.ACCESS_FINE_LOCATION)
        }

        // 如果权限列表不为空，则需要授权
        if( !permissionList.isEmpty() ){
            ActivityCompat.requestPermissions(this,
                permissionList.toTypedArray(), 2)
        }

    }
    private fun initLocation(){
        mLocationClient = LocationClient(applicationContext);
        //声明LocationClient类
        mLocationClient!!.registerLocationListener(myListener);
        //注册监听函数

        val option = LocationClientOption()

        option.setIsNeedLocationDescribe(true);
        //可选，是否需要位置描述信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的位置信息，此处必须为true

        mLocationClient!!.locOption = option;
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明

        mLocationClient!!.start()
    }

    private inner class MyLocationListener: BDLocationListener {
        override fun onReceiveLocation(location: BDLocation) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取位置描述信息相关的结果
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            val locationDescribe = location.locationDescribe //获取位置描述信息
            tvGetAddress.text = locationDescribe
        }
    }
    fun load(){

        try {
            val input = openFileInput(file_name2)
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    val info = parseAddress(it)
                    shouhuo_address_data.add(info)
                }
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
    }

    fun parseAddress(address_str:String):ShouhuoAddress{
        val str = address_str.split(",")
        val splitIndex = address_str.indexOf(",")
//        val shouhuo_name = address_str.substring(0,splitIndex).trim()
//        val shouhuo_number = address_str.substring(splitIndex+1,splitIndex).trim()
        val shouhuo_name = str[0]
        val shouhuo_number = str[1]
        val shouhuo_address = str[2]
        return ShouhuoAddress(shouhuo_name,shouhuo_number,shouhuo_address)
    }
    fun refreshAddress(){
        val adapter = ShouhuoAddressAdapter(shouhuo_address_data)
        recyclerviewshouhuoAddress.adapter = adapter
    }
    fun save(){
        try {
            val output = openFileOutput(file_name2, Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                for(item in shouhuo_address_data){
                    writer.write("${item.shouhuo_name},${item.shouhuo_number},${item.shouhuo_address}")
                    writer.newLine()
                }
            }
        }
        catch (e: IOException) {
            e.printStackTrace()
        }
    }
    fun show(){
        if(shouhuo_address_data.size > 10){
            shouhuo_address_data.remove(shouhuo_address_data.last())
        }
    }


}